/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University. All rights reserved.
 * 
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 * 1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license; 2) All redistributions in binary form
 * must reproduce the above copyright notice, this list of conditions and the
 * disclaimer listed in this license in the documentation and/or other materials
 * provided with the distribution; 3) Any documentation included with all
 * redistributions must include the following acknowledgement:
 * 
 * "This product includes software developed by the Community Grids Lab. For
 * further information contact the Community Grids Lab at
 * http://communitygrids.iu.edu/."
 * 
 * Alternatively, this acknowledgement may appear in the software itself, and
 * wherever such third-party acknowledgments normally appear.
 * 
 * 4) The name Indiana University or Community Grids Lab or NaradaBrokering,
 * shall not be used to endorse or promote products derived from this software
 * without prior written permission from Indiana University. For written
 * permission, please contact the Advanced Research and Technology Institute
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202. 5) Products
 * derived from this software may not be called NaradaBrokering, nor may Indiana
 * University or Community Grids Lab or NaradaBrokering appear in their name,
 * without prior written permission of ARTI.
 * 
 * 
 * Indiana University provides no reassurances that the source code provided
 * does not infringe the patent or any other intellectual property rights of any
 * other entity. Indiana University disclaims any liability to any recipient for
 * claims brought by any other entity based on infringement of intellectual
 * property rights or otherwise.
 * 
 * LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO
 * WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 * NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF
 * INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS.
 * INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS",
 * "VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.
 * LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR
 * ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION
 * GENERATED USING SOFTWARE.
 */
package cgl.narada.matching.integer;

import java.util.Enumeration;
import java.util.Hashtable;

import cgl.narada.event.NBEvent;
import cgl.narada.event.TemplateProfileAndSynopsisTypes;
import cgl.narada.matching.MatchingTree;
import cgl.narada.matching.Profile;
import cgl.narada.protocol.Destinations;
import cgl.narada.protocol.ProfilePropagationProtocol;

/**
 * This class implements the integer matching algorithm. This provides methods
 * to add a subscription and also to remove interest in a subscription
 * predicate. The matching algorithm should also be able to compute
 * destinations.
 * 
 * @author Shrideep Pallickara $Revision$ $Date$
 */

public class ClientIntegerMatching implements MatchingTree,
    IntegerMatchingDebugFlags {
    /** Profile Propagation Handler */
    private ProfilePropagationProtocol profilePropagationProtocol;

    /** The unit level for this matching tree */
    private int unitLevel;

    /** The system level */
    private int systemLevel;

    /** The destination for this node */
    Destinations thisDestination;

    /** contains a mapping of profileId's to a given destination */
    private Hashtable destinationsInfo;

    /** contains a mapping of destinations associated with a given profile */
    private Hashtable profilesAndDestinations;

    /** Mapping of profiles Id's to individual destinations */
    private Hashtable profileIds;

    private String moduleName = "ClientIntegerMatching: ";

    private int numTimesListed = 0;

    /** The IntegerMatching constructor */
    public ClientIntegerMatching(int unitLevel, int systemLevel,
        ProfilePropagationProtocol profilePropagationProtocol) {
        this.unitLevel = unitLevel;
        this.systemLevel = systemLevel;
        this.profilePropagationProtocol = profilePropagationProtocol;
        destinationsInfo = new Hashtable();
        profilesAndDestinations = new Hashtable();
        profileIds = new Hashtable();
    }

    /**
     * This method returns the level assocaited with this matching tree. A node
     * could be a gateway at multiple levels. How it handles destinations at
     * different levels, and propagates destinations at different levels is
     * dicatated by the level of the matching tree which computes the
     * destinations and initiates profile propagation changes.
     * 
     * @return The level of the matching tree.
     */
    public int getMatchingLevel() {
        return unitLevel;
    }

    /** This method sets the destination address for this node */
    public void setNodeDestination(Destinations destination) {
        thisDestination = destination;
    }

    /**
     * This method adds a subscription profile to the matching tree
     * 
     * @param profile
     *            The profile comprising the subscription and the destination
     *            assocaited with the subscription.
     */
    public void addSubscriptionProfile(Profile profile) {
        IntegerProfile integerProfile = (IntegerProfile) profile;
        System.out.println(integerProfile.getSubscription());
        Integer destination = new Integer(integerProfile.getDestination());
        Object profileKey = integerProfile.getSubscription();
        String profileId = integerProfile.getProfileId();
        if (profileId == null) {
            System.out.println(moduleName + "Unacceptable profileID ["
                + profileId + "]");
            return;
        }
        if (profileIds.containsKey(profileId)) {
            System.out.println(moduleName + integerProfile
                + "=>>>Already registered");
            return;
        }
        profileIds.put(profileId, integerProfile);

        /**
         * Update the profile ids associated with a destination. If destination
         * is a new one, create a new hashtable for profile ids to be stored and
         * then associate this hashtable with the destination
         */
        if (destinationsInfo.containsKey(destination)) {
            ((Hashtable) destinationsInfo.get(destination)).put(profileId,
                                                                profileId);
        } else {
            Hashtable _profileIds = new Hashtable();
            _profileIds.put(profileId, profileId);
            destinationsInfo.put(destination, _profileIds);
        }

        /**
         * Update the destinations associated with a profile. If the profile is
         * a new one, create a new hashtable for the destinations to be stored
         * and then associate this hashtable with the profile
         */
        if (profilesAndDestinations.containsKey(profileKey)) {
            ((Hashtable) profilesAndDestinations.get(profileKey))
                .put(destination, integerProfile);
        } else {
            Hashtable _destinations = new Hashtable();
            _destinations.put(destination, integerProfile);
            profilesAndDestinations.put(profileKey, _destinations);
        }

        propagateChangesToHigherLevels(integerProfile, true);
    }

    public void removeSubscriptionProfile(Profile profile) {
        IntegerProfile integerProfile = (IntegerProfile) profile;
        removeProfileWithId(integerProfile.getProfileId());
        /** Propagate this loss of profile to the highest levels */
        // propagateChangesToHigherLevels(stringProfile, false);
    }

    public void removeProfilesForDestination(Object clientIdentifier,
                                             String linkId) {
        if (clientIdentifier == null || linkId == null) {
            System.out.println(moduleName + "ClientIdentifer=["
                + clientIdentifier + "] or LinkId=[" + linkId + "]");
            return;
        }
        long start = System.currentTimeMillis();
        if (!destinationsInfo.containsKey(clientIdentifier)) {
            if (ClientIntegerMatching_Debug) {
                System.out.println(moduleName + "Not aware of destination ["
                    + clientIdentifier
                    + "] submitted for removal from matching tree");
            }
            return;
        }

        Hashtable profileIdsToRemove = (Hashtable) destinationsInfo
            .get(clientIdentifier);
        Enumeration e = profileIdsToRemove.keys();
        while (e.hasMoreElements()) {
            Object _removeId = e.nextElement();
            removeProfileWithId(_removeId);
        }
        listSubscriptionTables(clientIdentifier, linkId);
        long end = System.currentTimeMillis();
        System.out.println(moduleName
            + "Processing time for removal of profiles" + " for client "
            + clientIdentifier + " with LinkId (" + linkId + ") ="
            + (end - start) + "milliseconds");
    }

    /** This method removes a subscription profile */
    public void removeProfileWithId(Object profileId) {
        if (profileId == null) {
            System.out.println(moduleName + "ProfileId for removal is null");
            return;
        }
        if (!profileIds.containsKey(profileId)) {
            /** This profile has of course been processed before. */
            System.out.println(moduleName
                + "Trying to remove non-existent profileId");
            return;
        }

        IntegerProfile integerProfile = (IntegerProfile) profileIds
            .get(profileId);
        Object profileKey = integerProfile.getSubscription();
        Integer destination = new Integer(integerProfile.getDestination());

        if (profilesAndDestinations.containsKey(profileKey)) {
            Hashtable _dests = (Hashtable) profilesAndDestinations
                .get(profileKey);
            if (_dests.containsKey(destination)) {
                _dests.remove(destination);
            }
            /**
             * If the destinations associated with a profile is reduced to zero,
             * remove the profile from the list of profiles.
             */
            if (_dests.size() == 0) {
                profilesAndDestinations.remove(profileKey);
            }
        }

        /** Remove the profileId from the list of profileId's being maintainied */
        profileIds.remove(profileId);
        /** Propagate this loss of profile to the highest levels */
        propagateChangesToHigherLevels(integerProfile, false);
    }

    public void propagateChangesToHigherLevels(Profile profile,
                                               boolean addProfile) {
        if (profilePropagationProtocol == null) {
            return;
        }
        IntegerProfile integerProfile = (IntegerProfile) profile;

        /**
         * The first step ofcourse is to replace lower level destinations with
         * the destination ID at the next higher level
         */
        if (ClientIntegerMatching_Debug) {
            System.out.println("The destination associated with profile "
                + integerProfile.getSubscription() + " is "
                + integerProfile.getDestination());
        }
        int temp = 0;
        int tempDest;
        for (; temp <= systemLevel;) {
            tempDest = thisDestination.getDestinationsAtLevel(temp);
            if (ClientIntegerMatching_Debug) {
                System.out.print("This destination would be replaced by "
                    + tempDest);
            }

            if (ClientIntegerMatching_Debug) {
                System.out.println(" for representation in a level(" + temp
                    + ") tree ");
            }
            IntegerProfile _propagateProfile = new IntegerProfile(
                                                                  (Integer) integerProfile
                                                                      .getSubscription(),
                                                                  tempDest,
                                                                  integerProfile
                                                                      .getProfileId());

            profilePropagationProtocol
                .propagateProfileChange(_propagateProfile, temp, addProfile);
            temp++;
        }
    }

    /**
     * This method return the destinations assocaited with an event that needs
     * to be matched to the matching tree
     * 
     * @return The destination as an INT
     */
    public Object matchEvent(NBEvent nbEvent) {
        Object profileKey = nbEvent.getContentSynopsis();
        return profilesAndDestinations.get(profileKey);
    }

    /** Returns the type of profiles managed by this matching engine */
    public int getManagedProfileType() {
        return TemplateProfileAndSynopsisTypes.INTEGER;
    }

    private void listSubscriptionTables(Object clientLost, String linkId) {

        if (profilesAndDestinations.size() == 0) {
            System.out.println(moduleName + "Subscription Table is EMPTY"
                + "Listing for the [" + (numTimesListed++) + "] time\n");
            return;
        }

        Enumeration e = profilesAndDestinations.keys();
        if (e == null) {
            System.out.println(moduleName
                + "listSubscriptionTable(): Enumeration is"
                + "null should NOT have happened");
            return;
        }

        String tableInfo = "\n" + moduleName + "After Loss of client ["
            + clientLost + "] from " + linkId + "\nSubscription Table Contents"
            + "Listed for the [" + (numTimesListed++) + "] time\n";
        while (e.hasMoreElements()) {
            String _profile = (String) e.nextElement();
            if (_profile.equals(null)) {
                System.out.println(moduleName + "listSubscriptionTable(): "
                    + "Enumeration is null should NOT have happened");
                continue;
            }
            int size = ((Hashtable) profilesAndDestinations.get(_profile))
                .size();
            tableInfo = tableInfo + _profile + " (" + size + ")\n";
        }
        System.out.println(tableInfo);

    }

    public static void main(String[] args) {
    }

}
